import { Input, Form, Button } from "antd-mobile";
import React, { memo } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

import { fetchLoginAction } from "@/store/modules/user";
import LoginWrapper from "./style";
const Login = memo((props) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const validemessage = {
    required: "${label}是必选字段",
    string: {
      range: "${label}至少${min}位 ",
    },
  };

  const onFinish = (values) => {
    dispatch(fetchLoginAction({ user: values.user, pwd: values.pwd }))
      .then((res) => {
        navigate("/home");
      })
      .catch((err) => {
        console.log(err);
      });
  };

  function register() {
    navigate("/register");
  }

  return (
    <LoginWrapper>
      <div className="login">
        <div className="title">很高兴 再次见到你！</div>
        <Form
          layout="horizontal"
          validateMessages={validemessage}
          onFinish={onFinish}
          footer={
            <div className="footer">
              <Button block type="submit" color="primary" size="large">
                登录
              </Button>
              <Button block color="primary" size="large" onClick={register}>
                注册
              </Button>
            </div>
          }
        >
          <Form.Item name="user" label="用户名" rules={[{ required: true }]}>
            <Input placeholder="请输入用户名"></Input>
          </Form.Item>
          <Form.Item
            name="pwd"
            label="密码"
            rules={[{ required: true }, { type: "string", min: 6 }]}
          >
            <Input placeholder="请输入密码" type="password"></Input>
          </Form.Item>
        </Form>
      </div>
    </LoginWrapper>
  );
});

export default Login;
